const Controller = require("egg").Controller;

class TestController extends Controller {
    // 测试 MySQL 性能（查询 users 表中的记录）
    async mysql() {
        const { ctx, app } = this;
        const start = Date.now();

        try {
            // 模拟查询操作
            const users = await app.model.Users.findAll({ limit: 10 }); // 随机查询部分数据
            ctx.body = {
                message: 'MySQL query executed',
                latency: Date.now() - start,
                data: users,
            };
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }

    // 测试 MySQL 写操作
    async mysqlWrite() {
        const { ctx, app } = this;
        const start = Date.now();

        try {
            // 模拟写入操作
            const user = await app.model.Users.create({
                username: `User-${Date.now()}`,
                password: "2134567",
                age: Math.floor(Math.random() * 50) + 20,
                phone: Date.now(),
                email: "appletest@qq.com"
            });
            ctx.body = {
                message: 'MySQL write executed',
                latency: Date.now() - start,
                data: user,
            };
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }

    // 测试 Redis 性能
    async redis() {
        const { ctx, app } = this;
        const key = `test:${Date.now()}`;
        const value = Math.random().toString();
        const start = Date.now();

        try {
            // 模拟 Redis 读写
            await app.redis.set(key, value);
            const result = await app.redis.get(key);
            ctx.body = {
                message: 'Redis operation executed',
                latency: Date.now() - start,
                result,
            };
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }
}

module.exports = TestController;
